const superagent = require('superagent');
const request = require('request');
const fs = require('fs');
const router = require('koa-router')({
    prefix: '/song'
});

// http://music.163.com/api/search/pc

const status = {
    '400': JSON.stringify({
        code: 400,
        msg: 'Bad Request'
    }),
    '403': JSON.stringify({
        code: 403,
        msg: 'Forbidden'
    })
};


router.post('/search', async (ctx, next) => {
    let {s, offset, limit, type} = ctx.request.body;
    s = s || '';
    offset = typeof offset === 'undefined' ? '0' : offset;
    limit = typeof limit === 'undefined' ? '20' : limit;
    type = typeof type === 'undefined' ? '1' : type;

    const isXMLHttpRequest = ctx.request.headers['x-requested-with'] === 'XMLHttpRequest';
    if (!isXMLHttpRequest) {
        ctx.throw(400, status['400']);
    } else {
        let res = await superagent
            .post('http://music.163.com/api/search/pc')
            .type('form')
            .send({
                s,
                offset,
                limit,
                type
            }).then(res => {
                return JSON.parse(res.text);
            });
        res = res.result.songs.map(obj => {
            return {
                ...obj,
                music: `https://music.163.com/song/media/outer/url?id=${obj.id}.mp3`
            }
        });
        ctx.body = res
    }
});

router.get('/download/:songid', async (ctx, next) => {
    const {songid} = ctx.params;
    /*ctx.set({
        // "Content-type": "application/octet-stream"
        "Content-type": "audio/mp3"
    });*/

    // request库能直接请求远程资源并返回流，superagent需要如何设置?
    let result = await request
        .get(`https://music.163.com/song/media/outer/url?id=${songid}.mp3`);

   /* let result = await superagent
        .get(`https://attachments-cdn.shimo.im/VX0s77HJxEEZEZgd/%E4%B8%AD%E6%96%87%E6%B5%8B%E8%AF%95.mp3`)
        .then(res=>{
            return res
          console.log(res.redirects)
            return res.redirects*
        })*/
    ctx.body = result
});

module.exports = router;